/**
* 系统管理  角色管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">

      <el-form-item label="搜索：">
        <el-input size="small" v-model="formInline.roleCodeOrName" placeholder="输入角色编码或名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small"
              :data="listData"
              height="500"
              highlight-current-row
              v-loading="loading"
              border
              element-loading-text="拼命加载中" style="width: 100%;" @selection-change="roleHandleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column sortable prop="roleName" label="角色名称" width="200">
      </el-table-column>
      <el-table-column sortable prop="roleCode" label="角色代码" width="200">
      </el-table-column>
      <el-table-column sortable prop="roleMemo" label="角色备注" width="200">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.roleMemo" placement="right" effect="light">
            <span>{{scope.row.roleMemo}}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column sortable prop="roleMemo" label="角色备注" width="200">
        <template slot-scope="scope">
            <span>{{scope.row.enable == 0? "启用":"停用"}}</span>
        </template>
      </el-table-column>
      <el-table-column sortable prop="modifier" label="修改人" width="150">
      </el-table-column>
      <el-table-column sortable prop="modifiedTime" label="修改时间" width="250">
        <template slot-scope="scope">
          <div>{{scope.row.modifiedTime|timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="creator" label="创建人" width="150">
      </el-table-column>
      <el-table-column sortable prop="createTime" label="创建时间" width="250">
        <template slot-scope="scope">
          <div>{{scope.row.createTime|timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="300" fixed="right">
        <template slot="header" slot-scope="scope">
          <el-button size="mini" type="danger" @click="enableRole('enable')">启用选中</el-button>
          <el-button size="mini" type="danger" @click="enableRole('disable')">停用选中</el-button>
          <el-button size="mini" type="danger" @click="deleteRole">删除选中</el-button>
        </template>

        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改角色</el-button>
          <el-button size="mini" type="success" @click="userAccess(scope.$index, scope.row)">关联用户</el-button>
          <el-button size="mini" type="success" @click="roleAccess(scope.$index, scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="角色编码" prop="roleCode">
          <el-input size="small" v-model="editForm.roleCode" auto-complete="off" placeholder="请输入角色编码" :disabled="title!='添加'"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input size="small" v-model="editForm.roleName" auto-complete="off" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色备注" prop="roleMemo">
          <el-input type="textarea" size="small" v-model="editForm.roleMemo" auto-complete="off" placeholder="请输入角色备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 关联用户 -->
    <el-dialog style="justify-items: center" title="关联用户" :visible.sync="userAccessshow" width="55%" @click='closeDialog("user")'>
      <div style="text-align: center;">
        <el-transfer
          filterable
          :filter-method="userFilterMethod"
          :titles="['未关联用户', '已关联用户']"
          filter-placeholder="请输入用户名称"
          v-model="userValue"
          :props="{key: 'id',label: 'userName'}"
          :data="userData"
          @change="userHandleChange">
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("user")'>关闭</el-button>
      </div>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog style="justify-items: center" title="分配权限" :visible.sync="funcAccessshow" width="55%" @click='closeDialog("user")'>
      <div style="text-align: center;">
        <el-transfer
          filterable
          :filter-method="funcFilterMethod"
          :titles="['未分配权限', '已分配权限']"
          filter-placeholder="请输入权限名称"
          v-model="funcValue"
          :props="{key: 'id',label: 'funcName'}"
          :data="funcData"
          @change="funcHandleChange">
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("func")'>关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import Pagination from '../../components/Pagination'
    import {Post, Get} from "../../api/axiosFun";

    export default {
        data() {
            return {
                nshow: true, //switch开启
                fshow: false, //switch关闭
                loading: false, //是显示加载
                editFormVisible: false, //控制编辑页面显示与隐藏
                userAccessshow: false, //控制数据权限显示与隐藏
                funcAccessshow: false, //控制数据权限显示与隐藏
                title: '添加',
                roleMultipleSelection: [],
                editForm: {
                    id: '',
                    roleCode: '',
                    roleName: '',
                    roleMemo: ''
                },
                // rules 表单验证
                rules: {
                    roleCode: [
                        {required: true, message: '请输入角色编码', trigger: 'blur'}
                    ],
                    roleName: [
                        {required: true, message: '请输入角色名称', trigger: 'blur'}
                    ]
                },
                formInline: {
                    pageIndex: 0,
                    pageSize: 10,
                    enable: null,
                    roleCodeOrName: ''
                },
                listData: [], //角色数据
                //参数role
                roleId: '',
                roleCode: '',
                // 分页参数
                pageparm: {
                    currentPage: 1,
                    pageSize: 10,
                    total: 10
                },

                //用户
                userValue: [], //已分配
                userData: [],  //未分配
                userFilterMethod(query, item) {
                    return item.userName.indexOf(query) > -1;
                },

                //菜单
                funcValue: [], //已分配
                funcData: [],  //未分配
                funcFilterMethod(query, item) {
                    return item.funcName.indexOf(query) > -1;
                },

            }
        },
        // 注册组件
        components: {
            Pagination
        },
        /**
         * 数据发生改变
         */

        watch: {},

        /**
         * 创建完毕
         */

        created() {
            this.getdata(this.formInline)
        },

        /**
         * 里面的方法只有被调用才会执行
         */

        methods: {
            // 获取角色列表
            getdata(parameter) {
                this.loading = true
                Get("/officeSystem/role/select", parameter)
                    .then(result => {
                        if(result.status == 200){
                            this.listData = result.data.resultList;
                            // 分页赋值
                            this.pageparm.currentPage = this.formInline.pageIndex
                            this.pageparm.pageSize = this.formInline.pageSize
                            this.pageparm.total = result.data.totalCount;
                        }else{
                            // 分页赋值
                            this.pageparm.currentPage = 1
                            this.pageparm.pageSize = 10
                            this.pageparm.total = 0;
                        }
                        this.loading = false
                    })

            },
            // 分页插件事件
            callFather(parm) {
                this.formInline.pageIndex = parm.currentPage-1;
                this.formInline.pageSize = parm.pageSize;
                this.getdata(this.formInline);
            },
            // 搜索事件
            search() {
                this.formInline.pageIndex = 0;
                this.formInline.pageSize = 10;
                this.getdata(this.formInline);
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true
                if (row != undefined && row != 'undefined') {
                    this.title = '修改'
                    this.editForm.id = row.id
                    this.editForm.roleCode = row.roleCode
                    this.editForm.roleName = row.roleName
                    this.editForm.roleMemo = row.roleMemo
                } else {
                    this.title = '添加'
                    this.editForm.id = ''
                    this.editForm.roleCode = ''
                    this.editForm.roleName = ''
                    this.editForm.roleMemo = ''
                }
            },
            // 编辑、增加页面保存方法
            submitForm(editData) {
                this.$refs[editData].validate((valid) => {
                    if (valid) {
                        if(this.title == '修改'){
                          Post("/officeSystem/role/update", this.editForm)
                              .then(result => {
                                  if(result.status == 200){
                                      this.getdata(this.formInline);
                                      this.$message.success(result.message);
                                      this.editFormVisible = false;
                                  }else{
                                      this.$message.warning(result.message);
                                  }
                              })
                        }else{
                            Post("/officeSystem/role/insert", this.editForm)
                                .then(result => {
                                    console.log(result)
                                    if(result.status == 200){
                                        this.getdata(this.formInline);
                                        this.$message.success(result.message);
                                        this.editFormVisible = false;
                                    }else{
                                        this.$message.warning(result.message);
                                    }
                                })
                        }
                    } else {
                        this.editFormVisible = false;
                        return false;
                    }
                });
            },
            roleHandleSelectionChange(val){
                this.roleMultipleSelection = val;
            },
            //  启用/停用角色
            enableRole(enableType){
                if(this.roleMultipleSelection.length == 0){
                    this.$message.warning("请选择要操作的角色");
                    return;
                }
                Post("/officeSystem/role/enable", {
                    params: JSON.stringify({
                        "enableType": enableType,
                        "roleList": this.roleMultipleSelection
                    })
                }).then(result => {
                    if(result.status == 200){
                        this.getdata(this.formInline)
                        this.$message.success(result.message);
                    }else{
                        this.$message.error(result.message);
                    }
                })
            },
            // 删除角色
            deleteRole() {
                if(this.roleMultipleSelection.length == 0){
                    this.$message.warning("请选择要操作的角色");
                    return;
                }

                this.$confirm('此操作将永久删除选中角色, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    Post("/officeSystem/role/delete", {
                        roleList: JSON.stringify(this.roleMultipleSelection)
                    })
                        .then(result=>{
                            if(result.status == 200){
                                this.getdata(this.formInline);
                                this.$message.success(result.message);
                            }else{
                                this.$message.error(result.message);
                            }
                        })
                }).catch(() => {

                });

            },
            // 数据权限
            userAccess: function (index, row) {
                this.userAccessshow = true
                this.roleId = row.id
                this.roleCode = row.roleCode
                let params = {roleId:row.id}
                Get("/officeSystem/roleUser/getUsers", params)
                    .then(result=>{
                        if(result.status == 200){
                            this.userValue = result.data.list;
                            this.userData = result.data.unList;
                        }
                    })
            },
            roleAccess: function (index, row){
                this.funcAccessshow = true
                this.roleId = row.id
                this.roleCode = row.roleCode
                let params = {roleId:row.id}
                Get("/officeSystem/roleFunc/getFuncs", params)
                    .then(result=>{
                        if(result.status == 200){
                            this.funcValue = result.data.list;
                            this.funcData = result.data.unList;
                        }
                    })
            },

            userHandleChange(value, direction, movedKeys) {
                //可以通过direction回调right/left 来进行操作，right：把数字移到右边，left把数据移到左边
                if(direction === "right") {
                    let userList = []
                    for(let i=0; i<this.userData.length; i++){
                        for(let j=0; j<movedKeys.length; j++){
                            if(this.userData[i].id == movedKeys[j]){
                                userList.push(this.userData[i])
                            }
                        }
                    }
                    let params = {
                        roleId: this.roleId,
                        roleCode: this.roleCode,
                        userList: userList
                    }
                    Post("/officeSystem/roleUser/insert", {
                        params: JSON.stringify(params)
                    }).then(result => {
                        if(result.status == 200){
                            this.$message.success(result.message);
                        }else{
                            this.$message.error(result.message);
                        }
                    })
                }
                if(direction === "left") {
                    let userList = []
                    for(let i=0; i<this.userData.length; i++){
                        for(let j=0; j<movedKeys.length; j++){
                            if(this.userData[i].id == movedKeys[j]){
                                userList.push(this.userData[i])
                            }
                        }
                    }
                    let params = {
                        roleId: this.roleId,
                        roleCode: this.roleCode,
                        userList: userList
                    }
                    Post("/officeSystem/roleUser/delete", {
                        params: JSON.stringify(params)
                    }).then(result => {
                        if(result.status == 200){
                            this.$message.success(result.message);
                        }else{
                            this.$message.error(result.message);
                        }
                    })
                }
            },

            funcHandleChange(value, direction, movedKeys) {
                //可以通过direction回调right/left 来进行操作，right：把数字移到右边，left把数据移到左边
                if(direction === "right") {
                    let funcList = []
                    for(let i=0; i<this.funcData.length; i++){
                        for(let j=0; j<movedKeys.length; j++){
                            if(this.funcData[i].id == movedKeys[j]){
                                funcList.push(this.funcData[i])
                            }
                        }
                    }
                    let params = {
                        roleId: this.roleId,
                        roleCode: this.roleCode,
                        funcList: funcList
                    }
                    Post("/officeSystem/roleFunc/insert", {
                        params: JSON.stringify(params)
                    }).then(result => {
                        if(result.status == 200){
                            this.$message.success(result.message);
                        }else{
                            this.$message.error(result.message);
                        }
                    })
                }
                if(direction === "left") {
                    let funcList = []
                    for(let i=0; i<this.funcData.length; i++){
                        for(let j=0; j<movedKeys.length; j++){
                            if(this.funcData[i].id == movedKeys[j]){
                                funcList.push(this.funcData[i])
                            }
                        }
                    }
                    let params = {
                        roleId: this.roleId,
                        roleCode: this.roleCode,
                        funcList: funcList
                    }
                    Post("/officeSystem/roleFunc/delete", {
                        params: JSON.stringify(params)
                    }).then(result => {
                        if(result.status == 200){
                            this.$message.success(result.message);
                        }else{
                            this.$message.error(result.message);
                        }
                    })
                }
            },
            // 关闭编辑、增加弹出框
            closeDialog(dialog) {
                if (dialog == 'edit') {
                    this.editFormVisible = false
                } else if (dialog == 'user') {
                    this.userAccessshow = false
                } else if (dialog == 'func'){
                    this.funcAccessshow =false
                }
            }
        }
    }
</script>

<style>
  .user-search {
    margin-top: 20px;
  }
  .userRole {
    width: 100%;
  }
  .el-transfer{
    text-align: left;
    display: inline-block;
  }
  .el-transfer-panel{
    width: 300px;
  }
</style>

